﻿using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace tcplistener客户端
{
    class Program
    {
        static void Main(string[] args)
        {
            //当我们创建tcpclient对象的时候，就会跟server去建立连接
            TcpClient client = new TcpClient("127.0.0.1", 7788);

            NetworkStream stream = client.GetStream();//通过网络流进行数据的交换
            //ReadLine用来读取数据，write用来写入数据其实就是发送数据
            //利用一个死循环，重复向服务器端发送数据
            Thread thread = new Thread(()=>SendMsg(stream));    //开启发送消息
            thread.Start( );

            byte[] data = new byte[1024];//创建一个数据的容器，用来承接数据
            Thread t1 = new Thread(() => ReadMsg(stream, data));    //开启读取消息
            t1.Start();


            //stream.Close();
            //client.Close();
            //Console.ReadKey();

        }

        private static void ReadMsg(NetworkStream stream, byte[] data)
        {
            while (true)
            {
                //0 表示从数组的哪个索引开始存放数据
                //1024表示最大读取的字节数
                int length = stream.Read(data, 0, 1024);//读取数据
                string message = Encoding.UTF8.GetString(data, 0, length);
                Console.WriteLine("收到了消息:" + message);
            }
        }

        private static void SendMsg(NetworkStream stream)
        {
            while (true)
            {
                string message = Console.ReadLine();
                byte[] data = Encoding.UTF8.GetBytes(message);
                stream.Write(data, 0, data.Length);
            }
        }
    }
}
